package cn.tradewin.pmp.base;

import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.SessionState;

import cn.tradewin.common.wizard.Conversations;

public class ConversationalPage {

	private static final String WIZARD_CONVERSATION_PREFIX = "wiz";
	
	@SessionState
	protected Conversations conversations;

	private String conversationId = null;

	public void set(String conversationId) {
		this.conversationId = conversationId;
	}

	@Log
	String onPassivate() {
		return conversationId;
	}

	@Log
	Object onActivate() throws Exception {
		if (getConversationId() == null) {
			startConversation();
			return this;
		}
		return null;
	}
	
	@Log
	protected Object onActivate(String conversationId) throws Exception {
		this.conversationId = conversationId;
		return null;
	}

	protected void startConversation() {
		conversationId = conversations.startConversation(WIZARD_CONVERSATION_PREFIX);
	}

	protected void endConversation() {
		conversations.endConversation(conversationId);
		// If conversations SSO is now empty then remove it from the session
		if (conversations.isEmpty()) {
			conversations = null;
		}
	}

	protected String getConversationId() {
		return conversationId;
	}
}
